package com.google.code.irouter.plugin.sender;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.Validate;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.InputTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.SimpleNodeIterator;

import weibo4j.Weibo;
import weibo4j.WeiboException;
import weibo4j.http.AccessToken;
import weibo4j.http.HttpClient;
import weibo4j.http.PostParameter;
import weibo4j.http.RequestToken;

import com.google.appengine.api.datastore.Link;
import com.google.code.irouter.batch.api.Sender;
import com.google.code.irouter.model.Consumer;
import com.google.code.irouter.model.Queue;
import com.google.code.irouter.utils.LogUtil;
import com.google.code.irouter.utils.TextUtil;

public final class SinaSender extends Sender {

	private static final long serialVersionUID = -1630309208827781376L;

	private Weibo weibo;
	private RequestToken requestToken;
	private String token;
	private String tokenSecret;
	
	@Override
	protected void init(Consumer consumer) {
		System.setProperty("weibo4j.oauth.consumerKey", consumer.getConsumerKey());
		System.setProperty("weibo4j.oauth.consumerSecret", consumer.getConsumerSecret());
		weibo = new Weibo();
	}

	@Override
	protected void send(Consumer consumer, Queue queue, String fitMessage, Link remixedLink, Link file) throws Exception {
		weibo.setToken(token, tokenSecret);
		if(file != null) {
			try {
	        	String msgId = upload(consumer.getConsumerKey(), consumer.getConsumerSecret(), token, tokenSecret, TextUtil.contact(fitMessage, remixedLink.getValue()), file.getValue());
	        	if(msgId.length() == 0) {
	        		weibo.updateStatus(TextUtil.contact(fitMessage, remixedLink.getValue()));
	        	}
	     	} catch (Exception exception) {
				LogUtil.error(LogUtil.TYPE.BATCH, SinaSender.class, queue.getSolution(), "", exception);
				weibo.updateStatus(TextUtil.contact(fitMessage, remixedLink.getValue()));
			}
		} else {
			weibo.updateStatus(TextUtil.contact(fitMessage, remixedLink.getValue()));
		}
	}

	@Override
	protected boolean isRepost(Exception exception, boolean result) {
		return result;
	}

	@Override
	protected boolean auth(Consumer consumer) throws Exception {
		boolean result = true;
    	requestToken = weibo.getOAuthRequestToken();
    	Parser parser = new Parser();
    	String url = requestToken.getAuthorizationURL();
    	parser.setURL(url);
		parser.setEncoding(parser.getEncoding());		
		NodeList nodeList = parser.parse(new NodeClassFilter(InputTag.class));		
		SimpleNodeIterator simpleNodeIterator = nodeList.elements();
		List<PostParameter> postParameterList = new ArrayList<PostParameter>();
		while (simpleNodeIterator.hasMoreNodes()) {
			Node node = simpleNodeIterator.nextNode();
			InputTag inputnode = (InputTag) node;
			String name = inputnode.getAttribute("name");
			String value = inputnode.getAttribute("value");
			if (name.equals("userId"))
				value = consumer.getUser();
			else if (name.equals("passwd"))
				value = consumer.getPassword();
			try {
				Validate.notNull(value);
				PostParameter pp = new PostParameter(name, value);
				postParameterList.add(pp);
			} catch (IllegalArgumentException e) {
			}			
		}		
		PostParameter[] postParameters = postParameterList.toArray(new PostParameter[0]);
		String response = requestToken.getHttpClient().post(url, postParameters).asString();
		Pattern pattern = Pattern.compile("<span class=\"fb\">.*</span>");
		Matcher matcher = pattern.matcher(response);
		String pin = "";
		while (matcher.find())
		{  
		   pin = response.substring(matcher.start(), matcher.end()).replace("<span class=\"fb\">", "").replace("</span>", "");
		   break;
		}
		try {
			Validate.notEmpty(pin);
			AccessToken accessToken = requestToken.getAccessToken(pin);
			token = accessToken.getToken();
			tokenSecret = accessToken.getTokenSecret();
			
		} catch (IllegalArgumentException e) {
			result = false;
		}
		return result;
	}
	
	private String upload(String consumerKey, String consumerSecret, String tokenKey, String tokenSecret, String message, String url) {
		String result = "";
		List<PostParameter> postParameterList = new ArrayList<PostParameter>();
        postParameterList.add(new PostParameter("WB_AKEY", consumerKey));
        postParameterList.add(new PostParameter("WB_SKEY", consumerSecret));
        postParameterList.add(new PostParameter("WB_TOKEN", tokenKey));
        postParameterList.add(new PostParameter("WB_SECRET", tokenSecret));
        postParameterList.add(new PostParameter("text", message));
        postParameterList.add(new PostParameter("pic", url));
        PostParameter[] postParameters = postParameterList.toArray(new PostParameter[0]);        
        HttpClient client = new HttpClient();        
        try {
			result = client.post("http://tuandoudou.sinaapp.com/service/upload.php", postParameters).asString().trim();
		} catch (WeiboException e) {
		}
		return result;
	}

}